TOPDIR	:= $(shell if [ "$$PWD" != "" ]; then echo $$PWD; else pwd; fi)

LD	=ld -m elf_i386
CC	=gcc -D__KERNEL__
CPP	=$(CC) -E
NM	=nm
OBJCOPY =objcopy -O binary -R .note -R .comment -S
LINKFLAGS =-T $(TOPDIR)/kernel.lds

all: vmlinux

zImage: vmlinux boot/bootsect.bin boot/setup.bin
	rm -f zImage
	bximage -mode=create -fd=1.44M -q zImage
	$(OBJCOPY) vmlinux vmlinux.out
	dd if=boot/bootsect.bin of=zImage bs=512 count=1 conv=notrunc status=none
	dd if=boot/setup.bin of=zImage bs=512 count=4 seek=1 conv=notrunc status=none
	dd if=vmlinux.out of=zImage bs=512 count=1 seek=5 conv=notrunc status=none

vmlinux: kernel/head.o
	$(LD) $(LINKFLAGS) kernel/head.o -o vmlinux
	$(NM) vmlinux | grep -v '\(compiled\)\|\(\.o$$\)\|\( [aU] \)\|\(\.\.ng$$\)\|\(LASH[RL]DI\)' | sort > System.map

boot/%.bin: boot/%.S
	$(CPP) -traditional $< -o boot/$*.s
	nasm -o $@ boot/$*.s

kernel/head.o: kernel/head.S
	$(CC) -D__ASSEMBLY__ -m32 -traditional -c kernel/head.S -o kernel/head.o

run: zImage
	bochs -qf bochsrc

clean:
	rm -rf boot/*.bin boot/*.s vmlinux vmlinux.out zImage
	rm -rf System.map kernel/head.o
